package com.whz.generic.utils;

import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.util.ErrorHandler;

/**
 * 简单的任务定时器
 *
 * @author whz
 * 2021/8/19
 */
@Slf4j
@UtilityClass
public class TaskScheduleUtils {

    public static TaskScheduler getDefaultScheduler() {
        return createTaskScheduler("generic-timer", defaultThread(), t -> log.error("generic-timer异常.", t));
    }

    /**
     * 获取定时调度器
     *
     * @param prefix       调度器线程名前缀
     * @param errorHandler 错误处理器
     * @return 定时调度器
     */
    public static TaskScheduler createTaskScheduler(String prefix, int threads, final ErrorHandler errorHandler) {
        ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
        taskScheduler.setBeanName(prefix);
        taskScheduler.setPoolSize(threads);
        taskScheduler.setErrorHandler(errorHandler);
        taskScheduler.setDaemon(true);
        taskScheduler.initialize();
        return taskScheduler;
    }

    private int defaultThread() {
        return Math.max(1, Runtime.getRuntime().availableProcessors() >> 2);
    }
}